local tokensKey = KEYS[1]
local timestampKey = KEYS[2]
local rate = tonumber(ARGV[1])
local capacity = tonumber(ARGV[2])
local now = tonumber(ARGV[3])
local requested = tonumber(ARGV[4])

redis.log(redis.LOG_WARNING, "rate " .. ARGV[1])
local lastTokens = tonumber(redis.call('get', tokensKey))
if lastTokens == nil then
  lastTokens = capacity
end

local lastRefreshed = tonumber(redis.call('get', timestampKey))
if lastRefreshed == nil then
  lastRefreshed = now
end

local delta = math.max(0, now - lastRefreshed)
local filledTokens = math.min(capacity, lastTokens + (delta / 1000) * rate)
local allowed = filledTokens >= requested
local newTokens = filledTokens
if allowed then
  newTokens = filledTokens - requested
end

redis.call('set', tokensKey, newTokens)
redis.call('set', timestampKey, now)
-- or
-- redis.call('set', tokensKey, newTokens, 'EX', 60)
-- redis.call('set', timestampKey, now, 'EX', 60)


return allowed